//Developed by Rajarshi Roy
import java.awt.Robot; //java library that lets us take screenshots
import java.awt.AWTException;
import java.awt.event.InputEvent;
import processing.serial.*; //library for serial communication
import java.net.*;
import java.io.*;


Serial port; //creates object "port" of serial class
Robot robby; //creates object "robby" of robot class
ServerSocket s = null;

void setup()
{
  println(Serial.list());
	port = new Serial(this, Serial.list()[1],9600); //set baud rate
size(100, 100); //window size (doesn't matter)

	try {
  	s = new ServerSocket(1234);
	}
catch (IOException e) 
{
  e.printStackTrace(); }

	try //standard Robot class error check
	{
		robby = new Robot();
	}
	catch (AWTException e)
	{
		println("Robot class not supported by your system!");
		exit();
	}
}

void draw()
{
  float r=0F,g=0F,b=0F;

	while (true) {
		try {
			// wait here and listen for a connection
			Socket s1 = s.accept();
			//Get a communication stream associated with the socket
			InputStream os = s1.getInputStream();
			BufferedReader dos = new BufferedReader(new InputStreamReader(os));
			//Send your string! (UTF provides machine independence)
			String colors[] = dos.readLine().split(",");
			r = new Float(colors[0]);
			g = new Float(colors[1]);
			b=new Float(colors[2]);
			// close the connection, but not the server socket
			dos.close();
			os.close();
			s1.close();
		} catch (IOException e) {
			// ignore 
		} 
catch (Exception e)
{
}
port.write(0xff); //write marker (0xff) for synchronization
port.write((int)r+","+(int)g+","+(int)b+"\n"); //write blue value
}
	
}
